<template>
   <div>
        <a-card title="数据导入" :bordered="false" >
          <a-row >
            <a-col :span="6" v-show="currentTab === 0">
              <div>
                <a-upload
                  list-type="text"
                  :multiple = "true"
                  :file-list="fileList_finance_check"
                  :beforeUpload="beforeUpload"
                  accept=".xlsx,.xls"
                  @remove="removeFile">
                  <a-button>
                    <UploadOutlined />
                    选择文件
                  </a-button>
                </a-upload>
              </div>
            </a-col>
            <a-col :span="2" :offset="8">
                <a-button type="primary" @click="reset">重置</a-button>
            </a-col>
          </a-row>
        </a-card>
        <a-card  :bordered="false">
          <a-steps class="steps" :current="currentTab">
            <a-step title="信息补全" />
            <a-step title="确认入系统" />
            <a-step title="完成" />
          </a-steps>
          <div class="content" v-show="fileList_finance_check && fileList_finance_check.length>0">
            <step1 v-if="currentTab === 0" :files="fileList_finance_check" :queryParams="queryParams" :check-data="checkData"
                   :groupedTradePartners="checkBillStore.groupedTradePartners" :companies="checkBillStore.companies" @nextStep="nextStep"/>
            <step2 v-if="currentTab === 1" :queryParams="queryParams" :checkResult="checkResult" :check-data="checkData"
                   :groupedTradePartners="checkBillStore.groupedTradePartners" :companies="checkBillStore.companies" :table_loading="table_loading" @nextStep="nextStep" @prevStep="prevStep"/>
            <step3 v-if="currentTab === 2" @prevStep="prevStep" @finish="finish"/>
          </div>
        </a-card>
   </div>
</template>

<script setup>
import {ref, computed, onMounted, inject} from 'vue';
import { deleteAction, downFile, getAction, postAction, postDownFile } from "@/utils/request.js";
import moment from "moment";
import Step1 from './DataImportStep/Step1.vue';
import Step2 from './DataImportStep/Step2.vue';
import Step3 from './DataImportStep/Step3.vue';
import {ElMessage} from "element-plus";
import useCheckBillStore from "@/store/modules/checkBill.js";
import { useRouter } from 'vue-router'

const router = useRouter()
//dict
const checkBillStore = useCheckBillStore()
checkBillStore.getMyCompanies()
checkBillStore.getTradePartner()
const { proxy } = getCurrentInstance();
const dictOpts = proxy.useDict("bill_type");
// 响应式数据
const description = ref('Excel帐单核对');
const table_loading = ref(false);
const fileList_finance_check = ref([]);
const checkResult = ref({});
const checkData = ref({});
const currentTab = ref(0);
const queryParams = reactive({
  id_trader: {},
  searchText: {},
  id_myCompany: {}
})
const dateRange = ref({
  今天: [moment(), moment()],
  一周内: [moment().add(-6, 'day'), moment()],
  本月:  [moment().startOf('month'), moment().endOf('month')],
  上个月: [moment(new Date()).subtract(1,'months').startOf('month'),moment(new Date()).subtract(1,'months').endOf('month')],
  近三个月: [moment(new Date()).subtract(2,'months').startOf('month'),moment().endOf('month')],
});
const ipagination = ref({
  current: 1,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30','50','100'],
  showTotal: (total, range) => {
    return range[0] + "-" + range[1] + " 共" + total + "条"
  },
  showQuickJumper: true,
  showSizeChanger: true,
  total: 0
});
const dataSource = ref([]);
// simple vars
const url = {
  excel_loaded: "/yg/excel_loaded",
  getDataBySql: "/sys/getDataBySql"
}

// 方法
const changeUpClient = (text, record) => {
  if(text === record.text || !text) return;
  let sqlStr = `update YG_CheckingBillFromExcel set id_client=${text} where bill_no='${record.bill_no}'`;
  postAction(url.getDataBySql, {sql: sqlStr, isUpdate: true}).then(res => {
    if(res && res.success){
      ElMessage.success("保存成功！");
      record.id_client = text;
    } else {
      ElMessage.error("保存失败！");
    }
  }).catch((err) => {
    ElMessage.error("保存失败！");
    console.error(err && err.message);
  });
};

const nextStep = () => {
  //console.log("checkData:",JSON.stringify(checkData.value));
  if (currentTab.value < 2) {
    currentTab.value += 1;
  }
  if (currentTab.value === 1){
    genCheckList();
  }
};

const prevStep = () => {
  if (currentTab.value > 0) {
    currentTab.value -= 1;
  }
};

const finish = (args) => {
  console.log("finish:", args);
  //reset();
  if(args === 1) {
      router.push({
        path: '/finance/checkBill',
        query: {
          timestamp: Date.now()
        }
      })
  }
};

const reset = () => {
  fileList_finance_check.value=[]
  table_loading.value = false;
  checkData.value = {};
  checkResult.value = {};
  currentTab.value = 0;
  queryParams.id_trader = {}
  queryParams.searchText = {}
  queryParams.id_myCompany = {}
};

const genCheckList = () => {
  if( fileList_finance_check.value.length === 0 ) {
    ElMessage.error(`请先选择帐单excel文件！`);
    return false;
  }
  const formData = new FormData();
  fileList_finance_check.value.forEach((file) => {
    formData.append('files', file);
  });
  formData.append("id_traders", JSON.stringify(queryParams.id_trader));
  //console.error(formData);
  table_loading.value = true;
  postAction(url.excel_loaded, formData).then((res) => {
    if (!res) {
      ElMessage.warning("文件解析失败！");
      table_loading.value = false;
      return;
    }
    parseData(res.data);
    table_loading.value = false;
  }).catch((err) => {
    ElMessage.error(err.message);
    table_loading.value = false;
  });
};

const parseData = (dct) => {
  checkData.value = {};
  for (const key in dct) {
    checkData.value[key] = JSON.parse(dct[key]);
  }
  //console.error("checkData:", checkData.value);
};

const removeFile = (file) => {
  let position = fileList_finance_check.value.findIndex((f) => f.name === file.name);
  console.log("position:", position);
  if(position > -1) {
    fileList_finance_check.value.splice(position, 1);
  }
};

const beforeUpload = (file) => {
  var fileType = file.type;
  if (fileType.indexOf('excel') < 0 && fileType.indexOf('sheet') < 0) {
    ElMessage.error('请上传Excel表格文件');
    return false;
  }
  // console.log(file.name);
  // 用文件名验证，保持唯一
  if(!fileList_finance_check.value.find((f) => f.name === file.name)) {
    fileList_finance_check.value.push(file);
  }
  //console.log(fileList_finance_check.value);
  if(fileList_finance_check.value.length > 10) {
    ElMessage.error('一次上传，不能超过10个文件');
    return false;
  }
  // //console.error(fileList_finance_check.value);
  return false;
};

// 生命周期钩子
onMounted(() => {
  console.log("start mounting...")
  console.log("mounted...");
});
</script>
<style scoped>
/* tile uploaded pictures */
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline :deep(.ant-upload-animate-enter) {
  animation-name: uploadAnimateInlineIn;
}
.upload-list-inline :deep(.ant-upload-animate-leave) {
  animation-name: uploadAnimateInlineOut;
}
</style>
